package com.ruoyi.web.controller.common;

import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.IImageCleanupService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;

/**
 * MinIO文件上传控制器
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/minio")
public class MinioController extends BaseController
{
    @Value("${easy.minio.endpoint}")
    private String endpoint;
    
    @Value("${easy.minio.accessKey}")
    private String accessKey;
    
    @Value("${easy.minio.secretKey}")
    private String secretKey;
    
    @Value("${easy.minio.bucketName}")
    private String bucketName;

    @Autowired
    private IImageCleanupService imageCleanupService;


    /**
     * MinIO文件上传
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request)
    {
        try
        {
            if (file.isEmpty())
            {
                return AjaxResult.error("上传文件不能为空");
            }

            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename))
            {
                return AjaxResult.error("文件名不能为空");
            }

            String extension = "";
            if (originalFilename != null)
            {
                int lastDotIndex = originalFilename.lastIndexOf(".");
                if (lastDotIndex > 0)
                {
                    extension = originalFilename.substring(lastDotIndex);
                }
            }

            String fileName = UUID.randomUUID().toString().replace("-", "") + extension;
            
            try {
                MinioClient minioClient = MinioClient.builder()
                        .endpoint(endpoint)
                        .credentials(accessKey, secretKey)
                        .build();

                boolean bucketExists = minioClient.bucketExists(
                    BucketExistsArgs.builder().bucket(bucketName).build()
                );
                
                if (!bucketExists) {
                    minioClient.makeBucket(
                        MakeBucketArgs.builder().bucket(bucketName).build()
                    );
                }

                minioClient.putObject(
                    PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build()
                );

                logger.info("图片上传成功: {}", fileName);
                
            } catch (Exception e) {
                logger.error("MinIO上传失败: {}", e.getMessage(), e);
                return AjaxResult.error("MinIO上传失败：" + e.getMessage());
            }

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileName);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", fileName);
            ajax.put("originalFilename", originalFilename);
            return ajax;
        }
        catch (Exception e)
        {
            logger.error("MinIO文件上传异常", e);
            return AjaxResult.error("文件上传异常：" + e.getMessage());
        }
    }
}
